package org.micro.rbac.core.valid.validator;


import cn.hutool.core.util.ObjectUtil;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import org.micro.rbac.core.valid.Range;

import java.util.Arrays;

/**
 * @author hongsir
 * @apiNote 摘要:自定义字符串范围取值
 * @since 2019-05-29 08:53
 */
public class RangeValidator implements ConstraintValidator<Range, String> {

    private Range range;

    @Override
    public void initialize(Range range) {
        this.range = range;
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        // 如果 value 为空则不进行格式验证，为空验证可以使用 @NotBlank @NotNull @NotEmpty 等注解来进行控制，职责分离
        if (value == null || "".equals(value)) {
            return true;
        }
        String[] values = range.value();
        if (ObjectUtil.isEmpty(values)) {
            return true;
        }
        return Arrays.asList(values).contains(value);
    }

}
